package com.example.gadgeteer;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class ServerSocketService extends Service
{
	/*Some constants, representing the name of the server */
	public static final String PROTOCOL_SCHEME_L2CAP = "btl2cap";
	public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
	public static final String PROTOCOL_SCHEME_BT_OBEX = "btgoep";
	public static final String PROTOCOL_SCHEME_TCP_OBEX = "tcpobex";
	Bluetoothreceiver bluetoothReceiver;
	
	private static final String TAG = "gadgeteer";
	private Handler _handler = new Handler();
	
	
	/* GetDefaultAdapter */
	private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
	
	/* Server */
	private BluetoothServerSocket _serverSocket;
	
	/* Thread-Listen */
	private Thread _serverWorker = new Thread() {
		@Override
		public void run() {
			listen();
		};
	};
   @Override
   public void onCreate() {
      super.onCreate();
      Toast.makeText(this,"Service created ...", Toast.LENGTH_SHORT).show();
      bluetoothReceiver = new Bluetoothreceiver();
      IntentFilter filter = new IntentFilter();
      //filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
      filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
      filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
      this.registerReceiver(bluetoothReceiver, filter);
		/* Start listen */
		_serverWorker.start();  
   }
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(bluetoothReceiver);
		Toast.makeText(this,"Service destroyed ...", Toast.LENGTH_SHORT).show();
		shutdownServer();
	}
	private void shutdownServer() {
		new Thread() {
			@Override
			public void run() {
				_serverWorker.interrupt();
				if (_serverSocket != null) {
					try {
						/* close sever */
						_serverSocket.close();
					} catch (IOException e) {
						Log.e(TAG, "", e);
					}
					_serverSocket = null;
				}
			};
		}.start();
	}
	
	protected void listen() {
		try {
			
			_serverSocket = _bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
			UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
			/* accept client request */
			BluetoothSocket socket = _serverSocket.accept();
			Log.d(TAG, ">>Accept Client Request");
		    String message = "Hello from Android.\n";
		    byte[] msgBuffer = message.getBytes();
		    OutputStream outStream = socket.getOutputStream();
		    outStream.write(msgBuffer);
		    
			/* Processing the request content*/
			if (socket != null) {
			
			}
			} catch (IOException e) {
				Log.e(TAG, "", e);
			} 
	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		return null;
	}
	
	class Bluetoothreceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	       final String action = intent.getAction();
	       if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
	      	 Toast.makeText(ServerSocketService.this,"disconnected ...", Toast.LENGTH_SHORT).show();
	      	 //
		      	Thread tt = new Thread(){
		      		@Override
						public void run(){
		      		startService(new Intent(getApplicationContext(),LocationService.class));
		      		}
		      	};
		      		tt.start();
	      	 //
	      	 ServerSocketService.this.stopSelf();
	       }
	       if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
	      	 Toast.makeText(ServerSocketService.this,"connected ...", Toast.LENGTH_SHORT).show();
	       }        
	     //  if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
//	            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
//	            switch (state) {
//	            case BluetoothAdapter.STATE_DISCONNECTING:
//	                Log.d("gadgeteer","disconnecting");
//	                Toast.makeText(ServerSocketService.this,"disconnecting ...", Toast.LENGTH_SHORT).show();
//	                break;
//	            case BluetoothAdapter.STATE_DISCONNECTED:
//	                Log.d("gadgeteer","disconnected");
//	                Toast.makeText(ServerSocketService.this,"disconnected ...", Toast.LENGTH_SHORT).show();
//	                break;
//	            case BluetoothAdapter.STATE_TURNING_OFF:
//	            	Log.d("gadgeteer","turning off");
//	               Toast.makeText(ServerSocketService.this,"turning off ...", Toast.LENGTH_SHORT).show();
//	                break;
//	            case BluetoothAdapter.ERROR:
//	            	Log.d("gadgeteer","Error");
//	               Toast.makeText(ServerSocketService.this,"Error ...", Toast.LENGTH_SHORT).show();
//	                break;
//	            }
	      //  }
	     }
	 }
}

